package toubiao.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import toubiao.utils.excel.ExcelFactory;
import toubiao.utils.excel.domain.ExcelModel;
import toubiao.utils.excel.domain.ExcelModelColumn;
import utils.UtilBean;

public class ProUtilExcel {

	
	    /**
	    * @Title: list2Excel
	    * @Description: 生成exce文件，
	    * @param @param fileAbsPath 
	    * @param @param list
	    * @param @param excelModel
	    * @param @throws IOException    
	    * @return void    
	    * @throws
	    */
	static public void list2ExcelFile(String fileAbsPath,List list,ExcelModel excelModel) throws IOException{
		Map<Integer, Map<Integer, Object>> sheetMap =createSheetMap(list, excelModel);
		
		Workbook workbook=ExcelFactory.createWorkbook();
		Sheet sheet=workbook.getSheetAt(0);
		CellStyle bodyCellStyle=ExcelFactory.getCommonBodyCellStyle(workbook);
		ExcelFactory.fillSheet(sheet, sheetMap, bodyCellStyle);
		Map<Integer, Integer> widthMap=new HashMap<>();
		for(ExcelModelColumn column:excelModel.getFieldMap().values()){
			Integer columnInteger=column.getNumber();
			if(columnInteger==null)
			{
				continue;
			}
			Integer width=column.getWidth();
			widthMap.put(columnInteger, width);
		}
		ExcelFactory.setColumnWith(sheet, widthMap);
		FileOutputStream saveFile=new FileOutputStream(fileAbsPath);
		workbook.write(saveFile);
		saveFile.close();
	}

	/** 获得 生成sheet 的 Map<Integer, Map<Integer, Object>>
	 * 默认第一列为序号：1，2，3，4
	 * 
	 * @param list
	 * @param excelMode
	 * @return
	 */
	public static Map<Integer, Map<Integer, Object>> createSheetMap(List list,ExcelModel excelModel){
		Map<Integer, Map<Integer, Object>> sheetMap=new HashMap<Integer, Map<Integer,Object>>();
		
		Collection<ExcelModelColumn> columnNames=excelModel.getFieldMap().values();
		
		
		Map<Integer, Object> headRowMap=new HashMap<>();
		headRowMap.put(0, "序号");
		for(ExcelModelColumn column:columnNames){
			String columName=column.getName();
			headRowMap.put(column.getNumber(), columName);
		}
		sheetMap.put(0, headRowMap);
		
		int j=1;
		for(Object projectGrid:list){
			Map<Integer, Object> rowMap=new HashMap<>();
			for(ExcelModelColumn column:columnNames){
				Integer columnNuber=column.getNumber();
				String filedName=column.getFiledName();
				Object value=UtilBean.getFieldValueByName(filedName, projectGrid);
				rowMap.put(columnNuber, value);
			}
			rowMap.put(0, j);
			sheetMap.put(j, rowMap);
			j++;
		}
		return sheetMap;
	}
}
